package com.chenqq.qsocket.handler;

import android.text.TextUtils;

import com.chenqq.qsocket.listener.SocketMessageListener;
import com.chenqq.qsocket.message.AcceptReceiveFileMessage;
import com.chenqq.qsocket.message.FileTask;
import com.chenqq.qsocket.message.RefuseReceiveFileMessage;
import com.chenqq.qsocket.message.RequestSendFileMessage;
import com.chenqq.qsocket.message.SocketMessage;
import com.chenqq.qsocket.tools.FileCheck;
import com.chenqq.qsocket.tools.FileUtil;
import com.chenqq.qsocket.tools.LogShow;

import java.io.File;
import java.io.IOException;
import java.net.SocketAddress;

import org.apache.mina.core.session.IoSession;
import org.json.JSONException;

/**
 * 请求发送文件信息
 */
public class RequestSendFileMessageHandler extends FileMessageHandler {

	@Override
	public void handleMessage(SocketMessage msg, IoSession session) throws JSONException {
		RequestSendFileMessage requestSendFileMessage = new RequestSendFileMessage(msg);
		RequestSendFileMessage.FileInfo fileInfo = requestSendFileMessage.getFileInfo();
		SocketAddress remoteAddress = session.getRemoteAddress();
		String replace = remoteAddress.toString().replace("/", "");
		String[] split = replace.split(":");
		LogShow.showV( "收到接收文件请求 : " + fileInfo.fileName + " id " + fileInfo.id);
		if (socketMessageListener!=null){
			socketMessageListener.showFileInfo(tag,"收到接收文件请求 : " + fileInfo.fileName + " id " + fileInfo.id);
		}
		long totalUsedSpace = fileInfo.fileSize+fileInfo.zippedFileSize;
		LogShow.showV( "预计占用空间 : " + totalUsedSpace + " Bytes ");
		File dir = new File(DOWNLOAD_PATH);
		if (!dir.exists()) {
			if (dir.mkdirs())
				try {
					LogShow.showV( "创建下载目录:" + dir.getCanonicalPath());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
		if (!dir.exists()) {
			LogShow.showV( "无法创建下载目录");
			RefuseReceiveFileMessage refuseReceiveFileMessage = new RefuseReceiveFileMessage(
					fileInfo.id, -1, "server error");
			session.write(refuseReceiveFileMessage);

			LogShow.showV( "拒绝接收文件");
			return;
		}
		File file = new File(DOWNLOAD_PATH  + File.separatorChar+ fileInfo.fileName);
		if (file.exists()&&file.length()>=fileInfo.fileSize){
			if (!TextUtils.isEmpty(fileInfo.md5)){
				LogShow.showV( "文件存在开始验证MD5 : "+fileInfo.md5);
				try {
					String md5 = new FileCheck().getFileMD5String(file);
					if (md5.equals(fileInfo.md5)){
						RefuseReceiveFileMessage refuseReceiveFileMessage =
								new RefuseReceiveFileMessage(fileInfo.id, 0,
										"文件已存在不需要重新下载");
						session.write(refuseReceiveFileMessage);
						if (socketMessageListener!=null){
							socketMessageListener.receiveFileSuccess(tag,split[0]);
						}
						LogShow.showV( "验证MD5成功不需要下载 : "+fileInfo.md5);
						return;
					}
				} catch (IOException exception) {
					LogShow.showE( "MD5验证错误重新下载文件 : "+exception.getMessage());
				}
			}
		}

		if (FileUtil.checkAvailableSize(new File(DOWNLOAD_PATH),
				totalUsedSpace)) {
			FileTask fileTask = new FileTask();
			fileTask.startTime = System.currentTimeMillis();
			fileTask.filePath = DOWNLOAD_PATH + File.separatorChar
					 + fileInfo.fileName;
			fileTask.md5 = fileInfo.md5;
			fileTask.id = fileInfo.id;
			fileTask.fileName = fileInfo.fileName;
			fileTask.zippedFileSize = fileInfo.zippedFileSize;
			fileTask.zippedFilePath = DOWNLOAD_PATH + File.separatorChar
					+ System.currentTimeMillis() + "_zipped_"
					+ fileInfo.fileName;
			fileTask.size = fileInfo.fileSize;
			fileTask.fileSegmentSize = fileInfo.fileSegmentSize;
			if (FileUtil.deleteFile(fileTask.zippedFilePath)
					&& FileUtil.deleteFile(fileTask.filePath)) {
				mRFileTasks.put(fileInfo.id, fileTask);
				AcceptReceiveFileMessage acceptReceiveFileMessage = new AcceptReceiveFileMessage(
						fileInfo.id);
				session.write(acceptReceiveFileMessage);
				LogShow.showV("同意接收文件:" + fileInfo.fileName + " 临时存放路径:"
						+ fileTask.zippedFilePath + " 目标路径 "
						+ fileTask.filePath);
			} else {
				LogShow.showV("无法删除:"+fileTask.zippedFilePath+" 或者 "+fileTask.filePath);
				RefuseReceiveFileMessage refuseReceiveFileMessage = new RefuseReceiveFileMessage(fileInfo.id, 1, "服务器文件系统异常");
				session.write(refuseReceiveFileMessage);
				return;
			}
		} else {
			LogShow.showV(DOWNLOAD_PATH + " 内存不足 ");
			RefuseReceiveFileMessage refuseReceiveFileMessage = new RefuseReceiveFileMessage(
					fileInfo.id, 0, "服务器硬盘不足");
			session.write(refuseReceiveFileMessage);
			LogShow.showV( " 拒绝接收文件 ");
		}

	}

}
